package pl.mobilebackup.comm.session;

import java.rmi.RemoteException;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import org.apache.activemq.ra.ActiveMQConnectionFactory;

public class ActiveMQSender implements SessionBean {

	private static final long serialVersionUID = 1L;
	
	private SessionContext context = null;
	
	private ActiveMQConnectionFactory factory;
	
	private Queue queue;

	public void ejbActivate() throws EJBException { }

	public void ejbPassivate() throws EJBException { }

	public void ejbRemove() throws EJBException {
		System.out.println("ActiveMQSender.ejbRemove()");
	}

	public void ejbCreate() throws CreateException {
		System.out.println("ActiveMQSender.ejbCreate()");
		
		try {
			InitialContext context = new InitialContext();
			
			Object resource = context.lookup("java:comp/env/ACTIVEMQ_FACTORY");
			factory = (ActiveMQConnectionFactory) resource;
			
			resource = context.lookup("java:comp/env/ACTIVEMQ_RESPONSE");
			queue = (Queue) resource;
		} catch (NamingException e) {
			e.printStackTrace();
		}
		
	}
	
	public void setSessionContext(SessionContext context) throws EJBException, RemoteException {
		this.context = context;
	}

	public SessionContext getSessionContext() {
		return context;
	}

	public void sendResponse(final String response) throws JMSException {
		Connection connection = factory.createConnection("pcs", "Wincor2008");
		connection.start();
		
		Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
		
		MessageProducer producer = session.createProducer(queue);
		producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		
		TextMessage message = session.createTextMessage(response.toString());
		System.out.println("->Send message: " + response);
		producer.send(message);
		
		session.close();
		connection.close();
	}
}
